<?php

class BookedController extends AdminController
{
    public $parentUrl;
    public $status;
    
    public function init() {
        parent::init();
        $this->parentUrl = $this->module->id . '/' . Yii::app()->getController()->getId();
    }

	public function actionView($id)
	{
        try{
            $this->layout = false;
            $data = Booked::model()->with('user','booked_details')->findByPk($id);


            echo $this->render('view',array(
                'model'=>$data,'parentUrl'=>$this->parentUrl
            ),true,true);           
        }catch (Exception $e){
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');              
        }       
	}
	public function actionCreate()
	{
            try{
                    $model=new Booked;

                    if(isset($_POST['Booked'])){
                            $model->attributes=$_POST['Booked'];
                            $model->validate();
                            if(!$model->hasErrors()){
                                if($model->save()){
                                    $this->redirect(array('view','id'=>$model->id));                           
                                }
                            }
                    }

                    $this->render('create',array(
                            'model'=>$model,
                    ));            
            }catch (Exception $e){
                    Yii::log("Invalid request. Please do not repeat this request again.");
                    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');             
            }
	}

	public function actionUpdate($id)
	{
//        try{
        date_default_timezone_set('UTC');
        $model=$this->loadModel($id);

        $current_stt = $model->status;
        $ticket = Ticket::model()->findByPk($model->ticket_id);
        //Check if event have been deleted
        if($ticket == null){
            $message = " Sorry! This event have been deleted! Please contact your administrator!";
            $this->render('update',array('message' => $message));
        }
        else{
            $event_id = $ticket->event_id;
            $user_id = Yii::app()->user->id;

            $this->current_url = Yii::app()->request->requestUri;

            $link = '';
            $link .= Yii::app()->getBaseUrl(true) . '/bookingsystem';
            if ((isset($model) && $model->lock_session == 0 && $model->user_lock == 0) || $model->user_lock == $user_id) {
                $model->lock_session = 1;
                $model->user_lock = $user_id;
                $model->save();  
                if(isset($_POST['Booked'])){
                    $model->attributes=$_POST['Booked'];
                    $model->validate();
                        //Update booked_details table with seat 
                    if (isset($_POST['Ticket'])) {
                        foreach ($_POST['Ticket']['seat'] as $key => $value) {
                            $booked_detail = BookedDetail::model()->findByPk($key);
                            $seat_json = $this->multiexplode(array(",",".","|",":",";"," "),$value);
                            $booked_detail->seat = CJSON::encode($seat_json);
                            $booked_detail->save();
                        }
                    }
                    if(!$model->hasErrors()){
                        if($model->quantity > $ticket->remain_quantity){
                            $model->quantity = $ticket->remain_quantity;
                        }

                        if ($current_stt == STATUS_PENDING) {
                                //Sub temporaty quantity for ticket Quantity On Hand
                            foreach ($model->booked_details as $key => $value) {
                                $tickets = Ticket::model()->findByPk($value->ticket_id);
                                $booked_details_table = BookedDetail::model()->findByPk($value->id);
                                $booked_details_table->temp_quantity = $value->quantity;
                                $booked_details_table->save();
                                $remain_quantity = $tickets->remain_quantity - $value->quantity;
                                if($remain_quantity < 0){
                                    $remain_quantity = 0;
                                }
                                $tickets->remain_quantity = $remain_quantity;
                                $tickets->save();
                            }
                            $model->deliver_user_edit = $user_id;
                            $model->deliver_edit_time = date('Y-m-d H:i');
                            $model->status = STATUS_DELIVER;

                        } elseif($current_stt == STATUS_DELIVER) {
                            foreach ($model->booked_details as $key => $value) {
                                $tickets = Ticket::model()->findByPk($value->ticket_id);
                                    // De-add ticket if quantity which customer get less than real quantity
                                if ($value->temp_quantity != null && $value->quantity < $value->temp_quantity) {
                                    $remain_quantity = $value->temp_quantity - $value->quantity;
                                    $tickets->remain_quantity = $tickets->remain_quantity + $remain_quantity;

                                    $tickets->save();
                                }
                                if($value->temp_quantity != null && $value->quantity > $value->temp_quantity){
                                    $remain_quantity = $value->quantity - $value->temp_quantity;
                                    $tickets->remain_quantity = $tickets->remain_quantity - $remain_quantity;

                                    $tickets->save();
                                }
                            }
                            $model->finish_user_edit = $user_id;
                            $model->finish_edit_time = date('Y-m-d H:i');
                            $model->payment_status = 1;
                            $model->status = STATUS_FINISH;
                        }
                    }
                    $dataJson[$model->ticket_id]= (isset($_POST['Booked']['so_ghe'])) ? $_POST['Booked']['so_ghe'] : array() ;   
                    $model->so_ghe = json_encode($dataJson);
                    $model->lock_session = 0;
                    $model->user_lock = 0;

                    if($model->save()){

                        if(isset($_POST['Sendmail'])){
                            SendEmail::sendMailSuccess($model);
                        }                            
                        $this->redirect(array('index'));                           
                    }
                }
                $this->render('update',array(
                    'model'=>$model,'parentUrl'=>$this->parentUrl
                    )); 
            }
            else{
                $message = "The booked order '". $model->ticket_order_number ."' is processing by another user. Please choose another booked order";
                $this->render('update',array(
                    'model'=>$model,
                    'parentUrl'=>$this->parentUrl,
                    'lockmessage' => $message
                    ));                     
            }
        }
    }
        

      
//       }catch (Exception $e){
//                Yii::log("Invalid request. Please do not repeat this request again.");
//               throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');               
//       }       

	public function actionDelete($id)
	{
             try{
                    $model = $this->loadModel($id);
                    // $model_book = Booked::model()->with('booked_details')->findByPk($id);
                    // if ($model_book) {
                    //     $model_book->
                    // }
                    if($model){
                        if ($model->booked_details != null) {
                            foreach ($model->booked_details as $booked_details) {
                                $booked_details->delete();
                            }
                        }                 
                        if($model->delete()){
                            $this->redirect(Yii::app()->createAbsoluteUrl($this->parentUrl .'/index'));   
                        }
                    } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');            
            }catch (Exception $e){
                    Yii::log("Invalid request. Please do not repeat this request again.");
                    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');               
            }        
	}

	public function actionIndex()
	{
//            try{
                    
                    $booked_details = BookedDetail::model()->with('ticket')->findAll();
                    //Calculate price for each records in booked_details table
                    foreach ($booked_details as $key => $value) {
                        if($value->total_price){
                            $price = $value->ticket->price * $value->quantity;
                            $details_model = BookedDetail::model()->findByPk($value->id);
                            $details_model->attributes = $value;
                            $details_model->total_price =  $price;
                            $details_model->save();
                        }                
                    }
                    $model =new Booked();

                    $status = NULL;
                    $date = null;
                    if(isset($_GET['status'])){
                        $status = $_GET['status'];
                    }
                    if (isset($_POST['Booked']['date'])) {
                        $date = $_POST['Booked']['date'];
                        $data = $model->with('booked_details')->getAll($status,date("Y-m-d",strtotime($date)));

                    }else{
                        // $date = date("Y-m-d",time());
                        $data=$model->with('booked_details')->getAll($status);
                    }
                    
                    //Update price record in booked table
                    foreach ($data as $key => $value) {
                        if ($value->total_price == null) {
                            $total = null;
                            foreach ($value->booked_details as $k => $v) {                        
                                $total += $v->total_price;
                            }
                            $book_model = Booked::model()->findByPk($value->id);
                            $book_model->attributes = $value;
                            $book_model->total_price = $total;
                            $book_model->save();
                        }
                        
                    }   
                                  
                    $this->render('index',array(
                            'data'=>$data,
                            'parentUrl'=>$this->parentUrl,
                            'start_date' => $date
                    ));           
//            }catch (Exception $e){
//                     Yii::log("Invalid request. Please do not repeat this request again.");
//                    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
//            }

	}
	public function loadModel($id)
	{
             try{
 		$model=Booked::model()->with('booked_details','user')->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;           
            }catch (Exception $e){
                    Yii::log("Invalid request. Please do not repeat this request again.");
                    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');             
            }       
	}
    public function actionCalculate_price_details()
    {
        if(isset($_POST['book'])){
            // $this->layout = FALSE;
            //Update price for each record in book_details table.
            $model_details = BookedDetail::model()->with('ticket')->findByPk($_POST['book']['detail_id']);
            $model_details->quantity = $_POST['book']['ticket_quantity'];
            $model_details->total_price = $model_details->ticket['price'] * $_POST['book']['ticket_quantity'];
            $model_details->save();
            //Update total price for book order -- Main Price of a order
            $model = Booked::model()->with('booked_details')->findByPk($_POST['book']['booked_id']);
            $total = null;
            foreach ($model->booked_details as $key => $value) {   
                $total += $value['total_price'];
            }
            $model->total_price = $total;
            $model->save();
            echo CJSON::encode('1');
            Yii::app()->end();
            // echo  $this->render('_form_update',array('model_details' => $model_details,'model'=>$model)); 
          
        }     
    }
    public function multiexplode ($delimiters,$string) {

        $ready = str_replace($delimiters, $delimiters[0], $string);
        $launch = explode($delimiters[0], $ready);
        return  $launch;
    }
    public function actionDelete_details(){
        if (isset($_POST['id'])) {
            $booked_details = BookedDetail::model()->findByPk($_POST['id']);
            if (isset($booked_details)) {
                $ticket = Ticket::model()->findByPk($booked_details->ticket_id);
                $ticket->remain_quantity = ((int)$ticket->remain_quantity + (int)$booked_details->temp_quantity);
                $ticket->save();
                $booked = Booked::model()->findByPk($booked_details->booked_id);
                $booked->total_price = ((int)$booked->total_price - (int)$booked_details->total_price);
                $booked->save();
                $booked_details->delete();
            }
            echo CJSON::encode(1);
            Yii::app()->end();
        }
        
    }
    public function actionAdd_details()
    {
        if(isset($_POST['event_id']) && isset($_POST['booked_id'])){
            // var_dump($_POST);die();
            $booked_id = $_POST['booked_id'];
            $criteria = new CDbCriteria();
            $criteria->compare('t.event_id', $_POST['event_id']);
            $criteria->addCondition("t.id not in (select b.ticket_id from booked_details b where b.booked_id = {$_POST['booked_id']})");
            $ticket = Ticket::model()->findAll($criteria);
            echo $this->renderPartial('add_details',array('ticket' => $ticket,'booked_id'=>$booked_id),true,true);
        }
        if (isset($_POST['BookedDetails'])) {
            foreach ($_POST['BookedDetails'] as $key => $value) {
                // $number = (int)$value['quantity'];
                if ((int)$value['quantity'] == 0) {
                    unset($_POST['BookedDetails'][$key]);
                }

            }
            foreach ($_POST['BookedDetails'] as $key => $bookeddetails) {             
                $booked_details = new BookedDetail();
                $booked_details->attributes = $bookeddetails;
                $booked_details->total_price = (int)$bookeddetails['quantity'] * (int)$bookeddetails['price'];
                $seat_json = $this->multiexplode(array(",",".","|",":",";"," "),$bookeddetails['seat']);
                $booked_details->seat = CJSON::encode($seat_json);
                
                $booked_details->save();
            }
            //Recalculate for total price
            $data = $this->loadModel($_POST['BookedDetails'][0]['booked_id']);
            $total = null;
            foreach ($data->booked_details as $k => $v) {                        
                $total += $v->total_price;
            }
            $data->total_price = $total;
            $data->save();
            $message = "Input Success!!";
            echo $this->renderPartial('add_details',array('message' => $message),true,true);
        }
        
    }


    public function actionExportExcel($type = 'excel')
    {
        $date = Yii::app()->request->getQuery('date', date('Y-m-d'));
        $exportTypeAllow = array('csv', 'excel');
        if (in_array($type, $exportTypeAllow)) {
            /**
             * @var Booked $model
             */
            $models = Booked::model()->findAllByAttributes(array('booked_date' => $date));

            if (count($models) == 0) {
                Yii::app()->user->setFlash('error', 'There is no record to export.');
                $this->redirect($this->createUrl('index'));
            }

            $phpExcelPath = Yii::getPathOfAlias('application.libs.phpexcel.Classes');
            spl_autoload_unregister(array('YiiBase', 'autoload'));
            include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');


            spl_autoload_register(array('YiiBase', 'autoload'));
            $objPHPExcel = new PHPExcel();
            $objPHPExcel->getProperties()->setCreator(Yii::app()->name)
                ->setLastModifiedBy(Yii::app()->name)
                ->setTitle("Booked-{$date}")
                ->setSubject("Booked-{$date}");
            $base = 2;
            //set title

            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $base, 'TimeOrder')
                ->setCellValue('B' . $base, 'TicketOrder#')
                ->setCellValue('C' . $base, 'Payment')
                ->setCellValue('D' . $base, 'Main Tittle')
                ->setCellValue('E' . $base, 'TicketCode')
                ->setCellValue('F' . $base, 'TicketCodeDes')
                ->setCellValue('G' . $base, 'Price')
                ->setCellValue('H' . $base, 'Quantity')
                ->setCellValue('I' . $base, 'SeatMap')
                ->setCellValue('J' . $base, 'Percentage')
                ->setCellValue('K' . $base, 'Percentage Reason')
                ->setCellValue('L' . $base, 'Total')
                ->setCellValue('M' . $base, 'Status');

            $objPHPExcel->getActiveSheet()
                ->getStyle('A'.$base.':M'.$base)
                ->applyFromArray(array(
                'fill' => array(
                    'type' => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb'=>'538DD5'),
                ),
                'font' => array(
                    'bold' => true,
                    'color' => array('rgb' => 'FFFFFF'),
                )
            ));

            $objPHPExcel->getActiveSheet()->setCellValue('A1', date('j-M-Y', strtotime($date)));
             //Next line

            foreach ($models as $model) {
                $base++;
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $base, $model->booked_time)
                    ->setCellValue('B' . $base, $model->ticket_order_number)
                    ->setCellValue('C' . $base, MyFunctionCustom::getPayment($model->payment_type))
                    ->setCellValue('D' . $base, MyFunctionCustom::getInfoEvent($model->event_id, 2))
                    ->setCellValue('E' . $base, 'N/A')
                    ->setCellValue('F' . $base, 'N/A')
                    ->setCellValue('G' . $base, 'N/A')
                    ->setCellValue('H' . $base, $model->quantity)
                    ->setCellValue('I' . $base, $model->seat)
                    ->setCellValue('J' . $base, $model->percentage)
                    ->setCellValue('K' . $base, $model->percentage_reason)
                    ->setCellValue('L' . $base, MyFunctionCustom::percentage_calculate($model->total_price,$model->percentage))
                    ->setCellValue('M' . $base, MyFunctionCustom::getStatusBooking($model->status));

                $parentLine=$base+1;

                /**
                 * @var BookedDetail $detail
                 */
                foreach ($model->booked_details as $i => $detail) {
                    $base++;
                    $seatMap = "";
                    if ($detail->seat != null) {

                        $seat = CJSON::decode($detail->seat);
                        foreach ($seat as $key => $value) {
                            echo $value . " ";
                        }
                    }

                    $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('E' . $base, $detail->ticket->ticket_code)
                        ->setCellValue('F' . $base, $detail->ticket->description_of_ticket)
                        ->setCellValue('G' . $base, $detail->ticket->price)
                        ->setCellValue('H' . $base, $detail->quantity)
                        ->setCellValue('I' . $base, $seatMap)
                        ->setCellValue('L' . $base, $detail->quantity * $detail->ticket->price);


                }
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('H' . ($parentLine-1), "=sum(H{$parentLine}:H{$base})");
                $objPHPExcel->getActiveSheet()
                    ->getStyle('A'.($parentLine-1).':M'.($parentLine-1))
                    ->applyFromArray(array(
                    'fill' => array(
                        'type' => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb'=>'CCC0DA'),
                    ),
                    'font' => array(
                        'bold' => true
                    )
                ));

            }

            $objPHPExcel->getActiveSheet()->getStyle('A2:J2')->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
            ob_end_clean();
            ob_start();

            if ($type == 'excel') {
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="' . $date . '.xlsx"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                $objWriter->save('php://output');
            } elseif ($type == 'csv') {
                $fileName = $date . '.csv';
                header('Content-Type: text/csv');
                header('Content-Disposition: attachment;filename="' . $fileName . '"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
                $objWriter->save('php://output');
            }
        }
    }

}
